package com.jijs.framework.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jijs.framework.CodeConstant;
import com.jijs.framework.dao.BaseDaoI;
import com.jijs.framework.model.EasyUIDataGrid;
import com.jijs.framework.model.PageHelper;
import com.jijs.framework.model.Tree;
import com.jijs.framework.model.pmodel.AdeRole;
import com.jijs.framework.model.pmodel.AdeUser;
import com.jijs.framework.model.tmodel.TadeModule;
import com.jijs.framework.model.tmodel.TadeRole;
import com.jijs.framework.model.tmodel.TadeUser;
import com.jijs.framework.util.StringUtil;

/**
 * 角色管理服务类
 * 
 * @author jijs
 *
 */
@Service
public class RoleManagerService {

	@Autowired
	private BaseDaoI<TadeRole> roleDao;
	@Autowired
	private BaseDaoI<TadeUser> userDao;
	@Autowired
	private BaseDaoI<TadeModule> resourceDao;

	public String add(AdeRole role, AdeUser user) {

		// 回传信息
		String msg = "";

		// 判断字典编号是否存在
		if (StringUtils.isBlank(role.getId())) {
			role.setId(StringUtil.generateUUID());
		}

		// 用于判断该角色是否已经存在
		Map<String, Object> paramCode = new HashMap<String, Object>();
		paramCode.put("roleName", role.getRoleName().trim());
		if (roleDao.count("select count(*) from TadeRole t where t.roleName = :roleName", paramCode) > 0) {
			msg = "roleExist";
		} else {
			// 保存TAdmDictionary
			TadeRole t = new TadeRole();
			BeanUtils.copyProperties(role, t);

			t.setRoleIsBuildin(CodeConstant.ROLE_ISNOT_BUILDIN);// 内置角色标识
			roleDao.save(t);
			// 刚刚添加的角色，赋予给当前的用户
			TadeUser tuser = userDao.get(TadeUser.class, user.getId());
			tuser.getTadeRoles().add(t);
			msg = "success";
		}
		return msg;

	}

	public AdeRole get(String id) {
		AdeRole r = new AdeRole();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		TadeRole t = roleDao.get(
				"select distinct t from TadeRole t left join fetch t.tadeModules resource where t.id = :id", params);
		if (t != null) {
			BeanUtils.copyProperties(t, r);

			Set<TadeModule> s = t.getTadeModules();
			if (s != null && !s.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (TadeModule tr : s) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					ids += tr.getId();
					names += tr.getModuleName();
				}
				r.setModuleIds(ids);
				r.setModuleNames(names);
			}
		}
		return r;
	}

	public void edit(AdeRole role) {
		TadeRole t = roleDao.get(TadeRole.class, role.getId());
		if (t != null) {
			BeanUtils.copyProperties(role, t);
		}
	}

	/**
	 * 少量修改，加了个排序，内置字段置顶，费内置字段排序
	 * 
	 * @param user
	 * @param roleType
	 * @param ph
	 * @return List<Role>
	 */
	public EasyUIDataGrid dataGrid(AdeUser user, PageHelper ph) {

		List<AdeRole> rl = new ArrayList<AdeRole>();
		List<TadeRole> tl = null;
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = null;

		hql = "from TadeRole t ";
		String orderBy = " order by t.roleIsBuildin desc,t.roleSort asc";

		tl = roleDao.find(hql + orderBy, params, ph.getPage(), ph.getRows());
		if (tl == null || tl.size() <= 0) {
			return null;
		}

		for (TadeRole t : tl) {

			AdeRole r = new AdeRole();
			BeanUtils.copyProperties(t, r);
			r.setIconCls("status_online");

			Set<TadeModule> s = t.getTadeModules();
			if (s != null && !s.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (TadeModule tr : s) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					ids += tr.getId();
					names += tr.getModuleName();
				}
				r.setModuleIds(ids);
				r.setModuleNames(names);
			}
			rl.add(r);
		}

		EasyUIDataGrid dg = new EasyUIDataGrid();
		dg.setRows(rl);
		dg.setTotal(roleDao.count("select count(*)" + hql, params));
		return dg;
	}

	public void delete(String id) {
		TadeRole t = roleDao.get(TadeRole.class, id);
		del(t);
	}

	private void del(TadeRole t) {
		roleDao.delete(t);
	}

	public List<Tree> tree(AdeUser user) {
		List<TadeRole> l = null;
		List<Tree> lt = new ArrayList<Tree>();

		Map<String, Object> params = new HashMap<String, Object>();
		if (user != null) {
			params.put("userId", user.getId());// 查自己有权限的角色
			l = roleDao.find(
					"select distinct t from TadeRole t join fetch t.tadeUsers user where user.id = :userId order by t.roleSort",
					params);
		} else {
			l = roleDao.find("from TadeRole t order by t.roleSort");
		}

		if (l != null && l.size() > 0) {
			for (TadeRole t : l) {
				Tree tree = new Tree();
				BeanUtils.copyProperties(t, tree);
				tree.setText(t.getRoleName());
				tree.setIconCls("status_online");

				lt.add(tree);
			}
		}
		return lt;
	}

	public List<Tree> allTree() {
		return this.tree(null);
	}

	public void grant(AdeRole role) {
		TadeRole t = roleDao.get(TadeRole.class, role.getId());
		Map<String, Object> params = new HashMap<String, Object>();
		List<String> idList = new ArrayList<String>();
		if (role.getModuleIds() != null && !role.getModuleIds().equalsIgnoreCase("")) {
			boolean b = false;
			for (String id : role.getModuleIds().split(",")) {
				idList.add(id);
			}
			params.put("idList", idList);
			t.setTadeModules(new HashSet<TadeModule>(
					resourceDao.find("select distinct t from TadeModule t where t.id in (:idList)",params)));
		} else {
			t.setTadeModules(null);
		}
	}
}
